package com.game.manager.service;

import com.game.manager.params.UserRequest;
import com.game.manager.params.UserResponse;
import com.game.manager.security.GmAuthenticationManager;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

@Service
@AllArgsConstructor
public class UserServiceImpl implements UserService {
    @Autowired
    private GmAuthenticationManager authenticationManager;

    @Autowired
    private JwtTokenService jwtTokenService;

    @Override
    public UserResponse register(UserRequest user) {
        UserResponse userResponse = new UserResponse();
        userResponse.setUsername(user.getUsername());
        return userResponse;
    }

    @Override
    public String login(UserRequest user) {
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword());
        Authentication authentication = authenticationManager.authenticate(authenticationToken); // если пользователя нет, то выбросит ошибку!

        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        List<String> authoritiesString = authorities
                .stream()
                .map(GrantedAuthority::getAuthority)
                .collect(Collectors.toList());

        return jwtTokenService.createToken(user.getUsername(), authoritiesString);
    }

    @Override
    public UserResponse getUserRole(String username) {
        UserResponse userResponse = new UserResponse();
        userResponse.setUsername(username);
        return userResponse;
    }
}
